package com.wytec.xywzxw.utils;

import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.model.FileInfo;
import com.qiniu.util.Auth;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class QiNiuUtils {

    @Value("${qiniu.access-key}")
    private String accessKey;
    @Value("${qiniu.secret-key}")
    private String secretKey;
    @Value("${qiniu.bucket-name}")
    private String bucket;
    @Value("${qiniu.domain}")
    private String domain;

    public Map<String, Object> getQiNiuBucketList(int type,String prefix) {

        Map<String, Object> typeMap = new HashMap<>();
        List<Map<String, Object>> imageList = new ArrayList<>();
        List<Map<String, Object>> videoList = new ArrayList<>();
        List<Map<String, Object>> objectList = new ArrayList<>();

        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.region0());
        Auth auth = Auth.create(accessKey, secretKey);
        BucketManager bucketManager = new BucketManager(auth, cfg);

        //每次迭代的长度限制，最大1000，推荐值 1000
        int limit = 1000;

        //delimiter 指定目录分隔符，列出所有公共前缀（模拟列出目录效果）。缺省值为空字符串
        String delimiter = "";
        //列举空间文件列表
        BucketManager.FileListIterator fileListIterator = bucketManager.createFileListIterator(bucket, prefix, limit, delimiter);
        while (fileListIterator.hasNext()) {
            //处理获取的file list结果
            FileInfo[] items = fileListIterator.next();
            for (FileInfo item : items) {
                if (item.fsize == 0) {
                    continue;
                }
                Map<String, Object> map = getStringObjectMap(item);
                if (type == 0){
                    objectList.add(map);
                }else {
                    if (item.mimeType.startsWith("image")) {
                        imageList.add(map);
                    } else if (item.mimeType.startsWith("video")) {
                        videoList.add(map);
                    } else {
                        objectList.add(map);
                    }
                }
            }

        }
        typeMap.put("image", imageList);
        typeMap.put("video", videoList);
        typeMap.put("object", objectList);
        return typeMap;
    }

    private Map<String, Object> getStringObjectMap(FileInfo item) {
        Map<String, Object> map = new HashMap<>();
        map.put("name", item.key);
        map.put("size", CommonUtils.getConversionFlows(item.fsize + ""));
        map.put("mimeType", item.mimeType);
        map.put("timeStamps", item.putTime / 10000);
        map.put("url", domain + item.key);
        map.put("time", CommonUtils.changeTimeStamps(item.putTime / 10000, "yyyy-MM-dd HH:mm:ss"));
        return map;
    }

}
